#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    labViewCord=new QLabel("View Cord: ");
    labViewCord->setMinimumWidth(150);
    ui->statusbar->addWidget((labViewCord));

    labSceneCord=new QLabel("Scene Cord: ");
    labSceneCord->setMinimumWidth(150);
    ui->statusbar->addWidget(labSceneCord);

    labItemCord=new QLabel("Item Cord: ");
    labItemCord->setMinimumWidth(150);
    ui->statusbar->addWidget(labItemCord);

    pixelValueAtCord=new QLabel("Value: ");
    pixelValueAtCord->setMidLineWidth(150);
    ui->statusbar->addWidget(pixelValueAtCord);

    // ui->View->setCursor(Qt::CrossCursor);
    ui->View->setMouseTracking(true);
    ui->View->setDragMode(QGraphicsView::RubberBandDrag);
    QObject::connect(ui->View, SIGNAL(mouseMovePoint(QPoint,QPoint,QPoint)), this, SLOT(on_mouseMovePoint(QPoint,QPoint,QPoint)));
   // QObject::connect(ui->View, SIGNAL(mouseClicked(QPoint)), this, SLOT(on_mouseClicked(QPoint)));

    scene=new QGraphicsScene();   // scene逻辑坐标系定义
    ui->View->setScene(scene);
    //iniGraphicsSystem();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::iniGraphicsSystem()
{
    // 构造GrphicsView的各项

    QRectF rect(-200, -100, 400, 200); // 左上角坐标， 宽度，高度
    scene=new QGraphicsScene(rect);   // scene逻辑坐标系定义
    ui->View->setScene(scene);

    // 画一个矩形框，大小等于scene
    QGraphicsRectItem *item=new QGraphicsRectItem(rect);
    item->setFlags(QGraphicsItem::ItemIsSelectable|QGraphicsItem::ItemIsFocusable);
    QPen pen;
    pen.setWidth(2);
    item->setPen(pen);
    scene->addItem(item);

    // 画一个位于scene中心的椭圆，测试局部坐标
    QGraphicsRectItem *item2=new QGraphicsRectItem(-100,-50,200,100);
    item2->setPos(0,0);
    item2->setBrush(QBrush(Qt::transparent));
    item2->setFlags(QGraphicsItem::ItemIsMovable|QGraphicsItem::ItemIsSelectable|QGraphicsItem::ItemIsFocusable);

    scene->addItem(item2);

    scene->clearSelection();
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if(event->key()==Qt::Key_Shift)
    {
        longX=longY;
    }
    if(itemRect!=nullptr&&itemRect->isSelected()&&event->key()==Qt::Key_Delete)
    {
        scene->removeItem(itemRect);
    }
}



void MainWindow::resizeEvent(QResizeEvent *event)
{
    // 窗口大小变化事件
    // ui->labViewSize
}

void MainWindow::on_mouseMovePoint(QPoint point,QPoint endPoint0, QPoint startPoint0)
{

    // 鼠标移动事件，point,endPoint0,startPoint0是Graphics View的坐标，物理坐标
    labViewCord->setText(QString::asprintf("View Cord: %d,%d", point.x(), point.y()));
    QPointF pointScene=ui->View->mapToScene(point);  // 转换到GraphicsScene坐标
    labSceneCord->setText(QString::asprintf("Scene Cord: %.0f,%.0f", pointScene.x(),pointScene.y()));

    QGraphicsItem *item=nullptr;
    item=scene->itemAt(pointScene, ui->View->transform());  // 获取光标下的图形项
    if(item!=nullptr)
    {
        pointItem=item->mapFromScene(pointScene);  // 图形项的局部坐标
        labItemCord->setText(QString::asprintf("Item Cord: %d,%d",static_cast<int>(pointItem.x()),static_cast<int>(pointItem.y())));
        // labItemCord->setText(QString::asprintf("Item Cord: %f,%f",pointItem.x(),pointItem.y()));

        QPointF startPointItem=item->mapFromScene(ui->View->mapToScene(startPoint0));  // 转换成QGraphicsItem的坐标
        QPointF endPointItem=item->mapFromScene(ui->View->mapToScene(endPoint0));
        longX=static_cast<unsigned int>(endPointItem.x())-static_cast<unsigned int>(startPointItem.x());
        longY=static_cast<unsigned int>(endPointItem.y())-static_cast<unsigned int>(startPointItem.y());
        startPoint=startPointItem.toPoint();

        if(image!=nullptr)
        {
            QRgb pixelValue=image->pixel(static_cast<int>(pointItem.x()),static_cast<int>(pointItem.y()));
            int value=(qGreen(pixelValue)+qRed(pixelValue)+qBlue(pixelValue))/3;
            pixelValueAtCord->setText(QString::asprintf("Value: %d", value));
        }
    }
}


void MainWindow::on_ROIButton_clicked(bool checked)
{
    if(pixmapItem==nullptr)   // 在选区域之前，得先存在图像
    {
        return;
    }
    if(itemRect!=nullptr)    // 如果已有ROI存在，则先删除
    {
        scene->removeItem(itemRect);
    }
    //if(itemRect==nullptr)
    {
        QPoint pScene=(startPoint);   // 将GraphicsView坐标转换为GraphicsScene坐标
        //qDebug()<<startPoint;
        QRectF rect(pScene.x(),pScene.y(), longX, longY); // 左上角坐标， 宽度，高度
        // 画一个位于scene中的矩形
        itemRect=new QGraphicsRectItem(rect);
       // item2->setPos(startPoint);   // 决定矩形位置
        //itemRect->setBrush(QBrush(Qt::transparent));
        QPen pen;
        pen.setWidth(1);
        pen.setStyle(Qt::DashDotLine);
        pen.setColor(Qt::red);
        itemRect->setPen(pen);
        itemRect->setFlags(QGraphicsItem::ItemIsMovable|QGraphicsItem::ItemIsSelectable|QGraphicsItem::ItemIsFocusable);
        scene->addItem(itemRect);
        // scene->clearSelection();   // 清除所有选择
    }
}

void MainWindow::on_readImage_clicked()
{
    if(pixmapItem!=nullptr)
    {
        scene->removeItem(pixmapItem);
    }
    if(itemRect!=nullptr)
    {
        scene->removeItem(itemRect);
    }
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "", tr("(*.*  *.png* *.bmp* *.jpg*"));
    if (fileName.isEmpty())
    {
        // QMessageBox::information(this, "Error Message", "Select File Failed");
        return;
    }
    ui->imagePath->setText(fileName);

    QFile f(fileName);
    if(!f.exists())
    {
        QMessageBox::critical(this,"Error","The selected file does not exist.");
        return;
    }
    image=new QImage(fileName);
    if(image->isNull())
    {
        QMessageBox::critical(this,"Error","The selected file has an unsupported format.");
        return;
    }
    int originalImageWidth=image->width();
    int originalImageHeight=image->height();

    scene->setSceneRect(0,0,originalImageWidth,originalImageHeight);
    QPixmap pixImage= QPixmap::fromImage(*image);
    pixmapItem=new QGraphicsPixmapItem(pixImage);

    scene->addItem(pixmapItem);
    // pixmapItem->setFlags(QGraphicsItem::ItemIsMovable);

    ui->View->viewport()->update();
    on_zoomImage_clicked();
}

void MainWindow::on_zoomImage_clicked()
{
    if(image==nullptr)
        return;
    int width=image->width();
    int height=image->height();
    QRect rect=ui->View->contentsRect();
    int availableWidth=rect.width()-ui->View->verticalScrollBar()->width();
    int availableHeight=rect.height()-ui->View->horizontalScrollBar()->height();
    if((width-availableWidth)>(height-availableHeight))
        ui->View->setZoomFactor((float)((float)availableWidth)/((float)width));
    else if(height>availableHeight)
        ui->View->setZoomFactor((float)((float)availableHeight)/((float)height));
    else
        ui->View->setZoomFactor(1.0);
}
